<template>
  <view class="quantity-control">
    <button @click="decrease" :disabled="quantity <= 1">-</button>
    <input 
      type="number" 
      v-model.number="quantity" 
      @input="onInputChange" 
      min="1"
    />
    <button @click="increase">+</button>
  </view>
</template>

<script>
export default {
  props: {
    value: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      quantity: this.value
    };
  },
  watch: {
    value(newVal) {
      this.quantity = newVal;
    }
  },
  methods: {
    increase() {
      this.quantity++;
      this.$emit('input', this.quantity);
      this.updateQuantity();
    },
    decrease() {
      if (this.quantity > 1) {
        this.quantity--;
        this.$emit('input', this.quantity);
        this.updateQuantity();
      }
    },
    onInputChange(event) {
      let newQuantity = Number(event.target.value);
      // 检查 newQuantity 是否是一个有效的数字
      if (isNaN(newQuantity) || newQuantity < 1) {
        uni.showToast({
          title: '请输入正确的数字',
          icon: 'none',
          duration: 1000,
        });
        newQuantity = 1; // 如果输入无效或小于1，则重置数量为1
      }
      this.quantity = newQuantity;
      this.$emit('input', this.quantity);
      this.updateQuantity();
    },

    updateQuantity() {
      // 发射事件到父组件以更新购物车中的数量
      this.$emit('quantity-updated', this.quantity);
    }
  }
};
</script>

<style scoped>
.quantity-control {
  display: flex;
  align-items: center;
}
button {
  width: 30px;
  height: 20px;
  font-size: 20px;
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: center; /* 水平居中对齐 */
  background-color: #fff; /* 按钮背景颜色 */
}
input {
  width: 30px; 
  text-align: center;
  border-radius: 4px; /* 添加边框圆角 */
}
</style>
